<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      #box1 {
        border: solid;
        background: rgb(228, 248, 197);
        width: 400px;
        height: 400px;
        padding: 10px;
        position: fixed;
        left: 200px;
        top: 100px;
      }

      #box2 {
        border: solid;
        width: 100px;
        height: 100px;
        background: rgb(255, 177, 163);
        position: absolute;
      }
    </style>
  </head>
  <body>
    <div id="box1">
      box1
      <div id="box2">box2</div>
    </div>

    <script>
      const box1 = document.getElementById("box1");
      const box2 = document.getElementById("box2");

      box2.onmousedown = function (e) {
        // 3. 或鼠标相对于box2左上角的坐标
        const ax = e.clientX - box1.offsetLeft - box2.offsetLeft;
        const ay = e.clientY - box1.offsetTop - box2.offsetTop;
        box1.onmousemove = function (e) {
          // 1. 获取鼠标相对于box1的坐标
          const x = e.clientX - box1.offsetLeft;
          const y = e.clientY - box1.offsetTop;
          // 2. 根据鼠标相对于box1的坐标移动box2
          box2.style.left = x - ax + "px";
          box2.style.top = y - ay + "px";
        };
      };

      box2.onmouseup = function (e) {
        // 3. 取消box1的处理函数，结束移动
        box1.onmousemove = null;
      };
    </script>
  </body>
</html>
